<template>
    <!-- 添加用户 -->
    <div>
        <el-card v-loading="loading">
            <template #header>
                <div>编辑用户</div>
            </template>
            <!-- 注意：一定要添加ref 用来获取当前添加用户表单对象-->
            <el-form ref="editform" :rules="rules" :model="form" label-position="right" label-width="100px">
                <!-- 注意：如果想参与验证就必须在标签中添加prop -->
                <el-form-item label="用户名" prop="username">
                    <el-input v-model="form.username"></el-input>
                </el-form-item>                
                <el-form-item label="邮箱" prop="email">
                    <el-input v-model="form.email"></el-input>
                </el-form-item>
                <el-form-item label="手机" prop="phone">
                    <el-input v-model="form.phone"></el-input>
                </el-form-item>
                <el-form-item label="性别">
                    <el-radio-group v-model="form.gender">
                        <el-radio label="1">男</el-radio>
                        <el-radio label="0">女</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="editloading">保存</el-button>
                    <el-button type="danger" @click="$router.push({name:'UsersIndex'})">取消</el-button>
                </el-form-item>
            </el-form>
        </el-card>        
    </div>
</template>
<script>
// 引入状态管理
import { mapActions } from 'vuex';
import dayjs from 'dayjs';
export default {
    props: ['id'], // 属性映射
    data() {
        return {
            loading: false,
            form: {
                gender: '1',
            },
            rules: { // 设定验证规则
                // 这里的username是form中的prop的username
                username: [
                    { required: true, message: '用户名不能为空', trigger: 'change' }, // tigger 表示触发验证的方式 不写就是默认值
                    // 自定义验证规则 注意自定义验证只需要一条就可以了，上面的required可以不用写
                    {
                        validator: (rule, value, callback) => {
                            if (/^\w{2,18}$/.test(value)) {
                                callback();
                            } else {
                                callback(new Error('用户名必须是2-18个字符'));
                            }
                        }, trigger: 'change'
                    },
                    {
                        validator: async (rule, value, callback) => {
                            if (value === this.user.username) {
                                return;
                            }
                            const { data } = await this.exist({
                                field: 'username',
                                value,
                            });
                            if (data) {
                                callback(new Error('用户名已存在'));
                            } else {
                                callback();
                            }
                        }, trigger: 'blur',
                    }
                ],
                email: [
                    { required: true, message: '邮箱不能为空', trigger: 'change' },
                    {
                        validator: (rule, value, callback) => {
                            if (/^\w+@\w+\.\w+$/.test(value)) {
                                callback();
                            } else {
                                callback(new Error('邮箱格式不正确'));
                            }
                        }, trigger: 'change'
                    },
                    {
                        validator: async (rule, value, callback) => {
                            if (value === this.user.email) {
                                return;
                            }
                            const { data } = await this.exist({
                                field: 'email',
                                value,
                            });
                            if (data) {
                                callback(new Error('邮箱已存在'));
                            } else {
                                callback();
                            }
                        }, trigger: 'change',
                    }
                ],
                phone: [
                    { required: true, message: '手机号不能为空', trigger: 'change' },
                    {
                        validator: (rule, value, callback) => {
                            if (/^1[3456789]\d{9}$/.test(value)) {
                                callback();
                            } else {
                                callback(new Error('手机号格式不正确'));
                            }
                        }, trigger: 'change'
                    },
                    {
                        validator: async (rule, value, callback) => {
                            if (value === this.user.phone) {
                                return;
                            }
                            const { data } = await this.exist({
                                field: 'phone',
                                value,
                            });
                            if (data) {
                                callback(new Error('手机号码已存在'));
                            } else {
                                callback();
                            }
                        }, trigger: 'change',
                    }
                ],
            },
            user:{}, // 保存数据
        }
    },
    // 通过id获取用户信息
    created() {
        this.getUserLoading();
    },
    methods: {
        ...mapActions('users', ['editUser', 'exist', 'getUser']),
        async getUserLoading() {
            this.loading = true;
            const { data } = await this.getUser(this.id);
            this.user = {
                ...data,
            };
            this.form = data;
            this.loading = false;
        },
        editloading() {
            this.loading = true;
            this.$refs.editform.validate(async (valid) => {
                if (valid) {
                    try {
                        await this.editUser({
                            id: this.id,
                            data:{
                                username: this.form.username,
                                gender:this.form.gender,
                                email: this.form.email,
                                phone: this.form.phone,
                            },
                        });
                        this.$message.success('编辑成功');
                        this.$router.push({ name: 'UsersIndex' });
                    } catch (error) {
                        this.$message.error(error.response.data.message);
                    }
                };
            });
            this.loading = false;
        }
    }
}
</script>